package com.zscat.mallplus.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

@Slf4j
public class WXSubscribeMsgUtil {
    private final HttpClient httpclient;

    public static WXSubscribeMsgUtil getInstance(){
        return new WXSubscribeMsgUtil();
    }

    public WXSubscribeMsgUtil() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(20000)
                .setConnectionRequestTimeout(3000)
                .build();
        httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();
    }
    /**
     * 发送微信消息(订阅消息)
     *
     * @param touser    用户 OpenID
     * @param templatId 模板消息ID
     * @param page      URL置空，则在发送后，点击模板消息会进入一个空白页面（ios），或无法点击（android）。
     * @param data      详细内容
     * @return
     */
    public static String sendWechatMsgToUser(String touser, String templatId, String page, JSONObject data, String token) {
//        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        JSONObject json = new JSONObject();
        json.put("touser", touser);
        json.put("url", page);
        json.put("template_id", templatId);
        json.put("data", data);
        try {
            JSONObject resultJson = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
            log.info("发送模板消息{}结果:{}", templatId,JSON.toJSONString(resultJson));
            String errmsg = (String) resultJson.get("errmsg");
            if (!"ok".equals(errmsg)) {  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

        return "success";
    }

    public String getAccessToken(String appid, String appSecret) throws Exception {
        HttpGet get = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret);
        HttpResponse response = httpclient.execute(get);
        String text = EntityUtils.toString(response.getEntity());
        log.info("调用token接口返回:{}",JSON.toJSONString(text));
        Map<String, Object> resultMap = JsonUtils.readJsonToMap(text);
        String accessToken = (String) resultMap.get("access_token");
        return accessToken;
    }

}
